package com.wande.dataplatform.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.wande.common.core.domain.R;
import com.wande.common.log.annotation.Log;
import com.wande.common.log.enums.BusinessType;
import com.wande.common.mybatis.core.page.PageQuery;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.common.web.core.BaseController;
import com.wande.dataplatform.domain.bo.QueryHistoryBo;
import com.wande.dataplatform.domain.dto.QueryExecuteDTO;
import com.wande.dataplatform.domain.dto.QueryResultDTO;
import com.wande.dataplatform.domain.vo.QueryHistoryVO;
import com.wande.dataplatform.service.IDataQueryService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 数据查询控制器
 *
 * @author wande
 */
@Validated
@RestController
@RequestMapping("/dataplatform/query")
@RequiredArgsConstructor
public class DataQueryController extends BaseController {

    private final IDataQueryService dataQueryService;

    /**
     * 执行查询
     */
    @SaCheckPermission("dataplatform:query:execute")
    @Log(title = "数据查询", businessType = BusinessType.OTHER)
    @PostMapping("/execute")
    public R<QueryResultDTO> executeQuery(@Valid @RequestBody QueryExecuteDTO dto) {
        return R.ok(dataQueryService.executeQuery(dto));
    }

    /**
     * 导出查询结果
     */
    @SaCheckPermission("dataplatform:query:export")
    @Log(title = "导出查询结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportQueryResult(@Valid @RequestBody QueryExecuteDTO dto,
                                   @RequestParam(defaultValue = "CSV") String format,
                                   HttpServletResponse response) throws IOException {
        byte[] data = dataQueryService.exportQueryResult(dto, format);

        String fileName = "query_result_" + System.currentTimeMillis();
        String contentType;
        String extension;

        switch (format.toUpperCase()) {
            case "CSV" -> {
                contentType = "text/csv";
                extension = ".csv";
            }
            case "JSON" -> {
                contentType = MediaType.APPLICATION_JSON_VALUE;
                extension = ".json";
            }
            case "EXCEL" -> {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                extension = ".xlsx";
            }
            default -> {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
                extension = ".dat";
            }
        }

        response.setContentType(contentType);
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(fileName + extension, StandardCharsets.UTF_8));
        response.getOutputStream().write(data);
        response.getOutputStream().flush();
    }

    /**
     * 查询历史记录列表
     */
    @SaCheckPermission("dataplatform:query:history:list")
    @GetMapping("/history/list")
    public TableDataInfo<QueryHistoryVO> historyList(QueryHistoryBo bo, PageQuery pageQuery) {
        return dataQueryService.queryHistoryList(bo, pageQuery);
    }

    /**
     * 查询历史记录详情
     */
    @SaCheckPermission("dataplatform:query:history:query")
    @GetMapping("/history/{id}")
    public R<QueryHistoryVO> getHistoryInfo(@PathVariable Long id) {
        return R.ok(dataQueryService.queryHistoryById(id));
    }

    /**
     * 删除历史记录
     */
    @SaCheckPermission("dataplatform:query:history:remove")
    @Log(title = "删除查询历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/history/{ids}")
    public R<Void> removeHistory(@PathVariable Long[] ids) {
        return toAjax(dataQueryService.deleteHistoryByIds(ids));
    }

    /**
     * 重新执行历史查询
     */
    @SaCheckPermission("dataplatform:query:execute")
    @Log(title = "重新执行查询", businessType = BusinessType.OTHER)
    @PostMapping("/history/{id}/reexecute")
    public R<QueryResultDTO> reExecuteHistory(@PathVariable Long id) {
        return R.ok(dataQueryService.reExecuteHistory(id));
    }
}
